<template>
  <div ref="container" class="dashboard-editor-container">
    <div class="menu-item">
      <VoiceBroadcast ref="voiceBroadcast" :default-enabled="false" />
      <screenfull id="screenfull" :mod-date.sync="containerDate" class="right-menu-item hover-effect" />
    </div>

    <!-- 语音通知组件 -->
    <voice-notification ref="voiceNotification" />

    <HeadTitle />
    <div class="contaier-main">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="10" :lg="8" :xl="8" style="height: 100%;">
          <BoxList
            ref="boxListRef"
            :table-h="tableH"
            :table-data="BoxListtableData"
            :has-more-data="hasMoreData"
            :is-loading="isLoading"
            @loadMore="onLoadMore"
            @dateChange="onDateChange"
            @tableIds="onTableIds"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="14" :lg="16" :xl="16">
          <IncomeMain
            :income-list="IncomeMainDate"
            :start-poll-type="startPollType"
            :chart-date="chartDate"
            @IncomeTypepage="onIncomeTypepage"
          />
        </el-col>
      </el-row>
    </div>

  </div>
</template>

<script>

import { list, days, getBuyOrderList } from '@/api/dashboard.js'
import HeadTitle from './components/HeadTitle'
import BoxList from './components/BoxList'
import IncomeMain from './components/IncomeMain'
import Screenfull from '@/components/Screenfull'
import VoiceBroadcast from './components/VoiceBroadcast.vue'
import VoiceNotification from '@/components/VoiceNotification'

export default {
  name: 'DashboardAdmin',
  components: {
    HeadTitle,
    BoxList,
    IncomeMain,
    Screenfull,
    VoiceBroadcast,
    VoiceNotification
  },
  data() {
    return {
      tableH: 0, // 初始化为0而不是空字符串
      BoxListtableData: [],
      IncomeMainDate: [],
      page: 1,
      size: 20,
      BoxListTotal: 0,
      BoxListIds: '',
      type: 'amount',
      datetimer: '',
      chartDate: [],
      containerDate: null, // 初始化为null
      isLoading: false,
      hasMoreData: true,
      currentTime: '',
      lastRequestTime: '',
      timer1: null,
      timer2: null,
      startPollType: false,
      voiceEnabled: false,
      localNotification: null,
      // 新增：播报相关状态
      isVoiceBroadcasting: false,
      broadcastProgressId: null,
      currentBroadcastIndex: 0,
      totalBroadcastCount: 0,
      broadcastCompletionCheck: null,
      progressInterval: null
    }
  },
  computed: {
    // 计算表格行样式，避免直接访问未定义的属性
  },
  mounted() {
    this.$nextTick(() => {
      // 安全地设置containerDate
      if (this.$refs.container) {
        this.containerDate = this.$refs.container
      }

      // 安全地获取表格高度
      this.getTableHeight()

      // 添加窗口大小变化监听
      window.addEventListener('resize', this.getTableHeight, false)

      // 初始化其他功能
      this.updateSystemTime()
      this.startPolling()

      // 设置定时器
      this.systemTimeInterval = setInterval(() => {
        this.updateSystemTime()
      }, 1000)
    })
  },
  created() {
    this.$nextTick(() => {
      this.listapi()
      this.getBuyOrderListApi()
    })
  },
  beforeDestroy() {
    // 组件销毁前清除所有定时器和监听器
    this.stopPolling()
    this.cleanupBroadcast()

    // 清除系统时间定时器
    if (this.systemTimeInterval) {
      clearInterval(this.systemTimeInterval)
    }

    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.getTableHeight, false)

    // 清除播报进度通知
    if (this.broadcastProgressId) {
      this.$voiceNotify.close(this.broadcastProgressId)
    }
  },
  methods: {
    // 更新系统时间
    updateSystemTime() {
      const now = new Date()
      this.currentTime = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
    },

    // 开始轮询
    startPolling() {
      // listapi接口：3分钟轮询一次（180000毫秒）
      this.timer1 = setInterval(() => {
        this.startPollType = true
        this.listapi()
      }, 180000)

      // getBuyOrderListApi接口：1分钟轮询一次（60000毫秒）
      this.timer2 = setInterval(() => {
        this.getBuyOrderListApi()
      }, 60000)
    },

    // 停止轮询
    stopPolling() {
      if (this.timer1) {
        clearInterval(this.timer1)
        this.timer1 = null
      }
      if (this.timer2) {
        clearInterval(this.timer2)
        this.timer2 = null
      }
    },

    // 清理播报相关资源
    cleanupBroadcast() {
      if (this.broadcastCompletionCheck) {
        clearInterval(this.broadcastCompletionCheck)
        this.broadcastCompletionCheck = null
      }

      if (this.progressInterval) {
        clearInterval(this.progressInterval)
        this.progressInterval = null
      }

      this.isVoiceBroadcasting = false
    },

    onDateChange(val) {
      this.datetimer = val
      this.page = 1
      this.BoxListtableData = []
      this.hasMoreData = true
      this.listapi()
      this.daysApi()
    },

    onTableIds(val) {
      if (val) {
        this.BoxListIds = val
        this.daysApi()
      }
    },

    onIncomeTypepage(val) {
      this.type = val
      this.daysApi()
    },

    async getBuyOrderListApi() {
      try {
        const res = await getBuyOrderList()
        console.log('获取订单数据:', res)

        if (res.data && res.data.length > 0) {
          const messages = this.formatDataToMessages(res.data)

          // 调用语音播报
          this.startVoiceBroadcast(messages, res.data)
        } else {
          console.log('没有新的订单数据')
        }
      } catch (error) {
        console.error('获取订单数据失败:', error)
        this.$voiceNotify.voiceError('获取订单数据失败')
      }
    },

    // 开始语音播报
    startVoiceBroadcast(messages, orderData) {
      if (!this.$refs.voiceBroadcast) {
        console.error('语音播报组件未初始化')
        return
      }

      // 清理之前的播报状态
      this.cleanupBroadcast()

      this.isVoiceBroadcasting = true
      this.totalBroadcastCount = messages.length
      this.currentBroadcastIndex = 0

      // 开始播报
      this.$refs.voiceBroadcast.speak(messages)

      // 启动进度监控
      this.startProgressMonitoring(orderData)
    },

    // 启动进度监控
    startProgressMonitoring(orderData) {
      let progressIndex = 0
      this.progressInterval = setInterval(() => {
        if (progressIndex < this.totalBroadcastCount) {
          this.currentBroadcastIndex = progressIndex + 1

          // 显示当前播报内容的通知
          if (progressIndex < orderData.length) {
            this.showOrderNotification(orderData[progressIndex], progressIndex + 1)
          }

          progressIndex++
        } else {
          clearInterval(this.progressInterval)
          this.progressInterval = null
        }
      }, 4000) // 假设每条消息播报需要4秒
    },

    // 显示单条订单通知
    showOrderNotification(order, index) {
      this.$voiceNotify.show({
        title: '下单成功',
        message: this.formatOrderMessage(order),
        type: 'success',
        duration: 3500,
        position: 'bottom-left',
        showClose: true,
        dangerouslyUseHTMLString: true
      })
    },

    // 格式化订单消息用于通知显示
    formatOrderMessage(order) {
      return `
        <div style="line-height: 1.5; font-size: 14px;">
          <div style="margin-bottom: 4px;">用户:<strong>${order.nickname}</strong>下单了<strong>${order.column_name}</strong>专栏的订单</div>
        </div>
      `
    },

    // 格式化订单时间
    formatOrderTime(timestamp) {
      if (!timestamp) return '未知时间'
      try {
        const date = new Date(timestamp)
        return date.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
      } catch (error) {
        console.error('格式化时间失败:', error)
        return '时间格式错误'
      }
    },

    // 将数据转换为播报消息
    formatDataToMessages(data) {
      if (!Array.isArray(data)) {
        console.warn('formatDataToMessages: 数据不是数组', data)
        return []
      }

      return data.map(item => {
        const nickname = item.nickname || '未知用户'
        const columnName = item.column_name || '未知专栏'
        const message = `用户${nickname}下单了${columnName}专栏的订单`
        console.log('播报消息:', message)
        return message
      })
    },

    async listapi() {
      if (this.isLoading) return
      this.startPollType = false

      this.isLoading = true
      try {
        const res = await list({ page: this.page, size: this.size, pay_time: this.datetimer })
        const { rows, ...otherData } = res.data

        if (this.page === 1) {
          this.BoxListtableData = rows
        } else {
          this.BoxListtableData = this.BoxListtableData.concat(rows)
        }

        this.BoxListIds = this.BoxListtableData.map(item => item.id).join(',')
        this.BoxListTotal = otherData.total
        this.hasMoreData = rows.length >= this.size

        this.IncomeMainDate = [{
          name: '总销售额', value: otherData.amount, type: 'amount'
        }, {
          name: '方案销售额', value: otherData.scheme, type: 'scheme'
        }, {
          name: 'VIP销售额', value: otherData.vip, type: 'vip'
        }, {
          name: '优惠卡销售额', value: otherData.card, type: 'card'
        }, {
          name: '总退款额', value: otherData.refund, type: 'refund'
        }]

        this.daysApi()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('数据加载失败')
      } finally {
        this.isLoading = false
      }
    },

    async onLoadMore(type) {
      if (!this.hasMoreData || this.isLoading) {
        return
      }

      this.page += 1
      await this.listapi()
    },

    // 安全地获取表格高度
    getTableHeight() {
      this.$nextTick(() => {
        try {
          const tableElement = document.getElementById('table')
          if (!tableElement) {
            console.warn('未找到表格元素，使用默认高度')
            this.tableH = 400 // 设置一个默认高度
            return
          }

          const rect = tableElement.getBoundingClientRect()
          const h = window.innerHeight
          const FooterHeight = 48
          const tableHeight = h - rect.top - FooterHeight

          // 确保高度是有效值
          this.tableH = Math.max(tableHeight, 200) // 最小高度200px
        } catch (error) {
          console.error('获取表格高度失败:', error)
          this.tableH = 400 // 出错时使用默认高度
        }
      })
    },

    daysApi() {
      days({ pay_time: this.datetimer, column_ids: this.BoxListIds, type: this.type }).then(res => {
        this.chartDate = res.data
      }).catch(error => {
        console.error('获取图表数据失败:', error)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  height: 100%;
  background-color: #19143D;
  position: relative;
  display: flex;
  flex-direction: column;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }

  .contaier-main {
    flex: 1;
    box-sizing: border-box;
    padding: 20px;
    overflow: hidden; /* 防止内容溢出 */
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}

@media (max-width:768px) {
  .dashboard-editor-container {
    overflow: auto; /* 改为auto而不是scroll */
  }
}

.main-left {
  height: 100%;
  padding: 20px;
}

.errLog-container {
  display: inline-block;
  vertical-align: top;
}

.menu-item {
  display: inline-block;
  padding: 0 8px;
  height: 100%;
  font-size: 18px;
  color: #5a5e66;
  vertical-align: text-bottom;
  position: absolute;
  right: 10px;
  top: 10px;
  z-index: 1;
  display: flex;
}

.right-menu-item {
  margin-left: 30px;

  &.hover-effect {
    cursor: pointer;
    transition: background .3s;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }
}

// 新增：语音播报状态指示器
.voice-broadcast-status {
  position: fixed;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(64, 158, 255, 0.9);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 1000;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);

  .voice-status-icon {
    margin-right: 8px;
    animation: pulse 1.5s infinite;
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}
</style>
